﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MinhTam.Objects;
using MinhTam.DataAccess.Web;

public partial class BangGiaVe : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            keyField.Value = Request.QueryString["keyid"];
            HelpControls.InitListTuyenDuong(ddlTuyenDuong);
            HelpControls.InitListLoaiXe(ddlLoaiXe);
            InitData();
            InitListDetail();
            txtMoTa.config.toolbar = HelpUtil.GetSimpleCKEditorConfig(this);
            txtMoTa.config.uiColor = HelpUtil.GetCKEditorUiColorAdmin(this);

        }
    }
    private void InitListDetail()
    {
        string sql = string.Format(@"SELECT ROW_NUMBER() OVER (ORDER BY td.BEN_DI,td.BEN_DEN, bgxc.BEN_DI,bgxc.BEN_DEN, lx.TEN_LOAI) STT,bgxc.*
,td.BEN_DI +' <=> '+td.BEN_DEN TEN_TUYEN_DUONG,
lx.TEN_LOAI TEN_LOAI_XE
FROM BANG_GIA_XE_CT bgxc
LEFT JOIN TUYEN_DUONG td ON bgxc.TUYEN_DUONG_ID=td.TUYEN_DUONG_ID
LEFT JOIN LOAI_XE lx ON lx.LOAI_XE_ID=bgxc.LOAI_XE_ID where bgxc.BANG_GIA_XE_ID={0} ", string.IsNullOrEmpty(keyField.Value) ? "-1" : keyField.Value);
        DataTable dt = SQLConnectWeb.GetTable(sql, BANG_GIA_XE_CT.sTableName);
        gridViewData.DataKeyNames = new string[] {            
            BANG_GIA_XE_CT.cl_BANG_GIA_XE_CT_ID,            
            BANG_GIA_XE_CT.cl_BANG_GIA_XE_ID,
            BANG_GIA_XE_CT.cl_TUYEN_DUONG_ID,
            BANG_GIA_XE_CT.cl_BEN_DI,
            BANG_GIA_XE_CT.cl_BEN_DEN,
            BANG_GIA_XE_CT.cl_LOAI_XE_ID, 
            BANG_GIA_XE_CT.cl_GIA_VE,
            BANG_GIA_XE_CT.cl_PHU_THU,
            BANG_GIA_XE_CT.cl_GHI_CHU,
        };
        gridViewData.AutoGenerateColumns = false;
        gridViewData.DataSource = dt;
        gridViewData.DataBind();
    }

    private void InitData()
    {
        btnDelete.OnClientClick = "return confirm('Bạn có chắc là muốn xóa bảng giá này?')";

        if (string.IsNullOrEmpty(keyField.Value))
        {
            lblNgayCapNhat.Text = "";
            lblNgayTao.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyy HH:mm");
            lblNguoiTao.Text = UserLogin.FULL_NAME(this);
            lblNguoiCapNhat.Text = "";
            lblNguoiCNCaption.Visible = false;
            lblNgayCNCaption.Visible = false;
            btnDelete.Visible = false;

            ckcApDung.Checked = true;

            divChiTiet.Visible = false;
        }
        else
        {
            divChiTiet.Visible = true;
            btnSave.Text = "Cập nhật";

            string sql = string.Format(@"SELECT  bg.BANG_GIA_XE_ID,bg.TEN_BANG_GIA,bg.MO_TA,bg.NGAY_TAO,ISNULL(bg.DANG_AP_DUNG,'N') DANG_AP_DUNG, bg.NGAY_CAP_NHAT,
            u.FULL_NAME NGUOI_TAO_NAME,
            u1.FULL_NAME NGUOI_CAP_NHAT_NAME
            FROM BANG_GIA_XE bg
            LEFT JOIN USERS u ON u.USERS_ID = bg.NGUOI_TAO
            LEFT JOIN USERS u1 ON u1.USERS_ID=bg.NGUOI_CAP_NHAT WHERE bg.BANG_GIA_XE_ID={0}", keyField.Value);
            DataTable dt = SQLConnectWeb.GetTable(sql, BANG_GIA_XE.sTableName);
            if (dt != null && dt.Rows.Count > 0)
            {
                lblNgayCapNhat.Text = dt.Rows[0][BANG_GIA_XE.cl_NGAY_CAP_NHAT].ToString() == "" ? "" : ((DateTime)dt.Rows[0][BANG_GIA_XE.cl_NGAY_CAP_NHAT]).ToString("dd/MM/yyyy HH:mm");
                lblNgayTao.Text = ((DateTime)dt.Rows[0][BANG_GIA_XE.cl_NGAY_TAO]).ToString("dd/MM/yyyy HH:mm");
                lblNguoiTao.Text = dt.Rows[0]["NGUOI_TAO_NAME"].ToString();
                lblNguoiCapNhat.Text = dt.Rows[0]["NGUOI_CAP_NHAT_NAME"].ToString();
                lblNguoiCNCaption.Visible = true;
                lblNgayCNCaption.Visible = true;
                txtTenBangGia.Text = dt.Rows[0][BANG_GIA_XE.cl_TEN_BANG_GIA].ToString();
                txtMoTa.Text = dt.Rows[0][BANG_GIA_XE.cl_MO_TA].ToString();
                ckcApDung.Checked = dt.Rows[0][BANG_GIA_XE.cl_DANG_AP_DUNG].ToString() == "Y";

            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(keyField.Value))
        {

            bool ok = false;
            if (ckcApDung.Checked)
            {
                string sqlUpdate = string.Format(@"UPDATE BANG_GIA_XE SET DANG_AP_DUNG = 'N'");
                ok = SQLConnectWeb.ExecSQL(sqlUpdate);
            }
            else ok = true;
            if (ok)
            {

                string sql = @"INSERT INTO BANG_GIA_XE(TEN_BANG_GIA, MO_TA,	NGUOI_TAO,	NGAY_TAO,		DANG_AP_DUNG) 
                        VALUES( @TEN_BANG_GIA,	@MO_TA, @NGUOI_TAO,	getdate(),	@DANG_AP_DUNG)";


                ok = SQLConnectWeb.ExecuteNonQuery(sql,
                        "@TEN_BANG_GIA", txtTenBangGia.Text,
                        "@MO_TA", txtMoTa.Text.Replace("'", ""),
                        "@NGUOI_TAO", UserLogin.USER_ID(this),
                        "@DANG_AP_DUNG", (ckcApDung.Checked ? "Y" : "N")
                      ) > 0;

            }
            if (ok)
            {
                DataTable dt = SQLConnectWeb.GetTable(string.Format(@"select top 1 BANG_GIA_XE_id from BANG_GIA_XE order by BANG_GIA_XE_id desc"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    keyField.Value = dt.Rows[0]["BANG_GIA_XE_id"].ToString();
                    btnSave.Text = "Cập nhật";

                    btnDelete.Visible = true;

                    lblNguoiCNCaption.Visible = true;
                    lblNgayCNCaption.Visible = true;
                    divChiTiet.Visible = true;
                }
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Tạo mới bảng giá không thành công!");
            }
        }
        else
        {
            bool ok = false;
            if (ckcApDung.Checked)
            {
                string sqlUpdate = string.Format(@"UPDATE BANG_GIA_XE SET DANG_AP_DUNG = 'N'");
                ok = SQLConnectWeb.ExecSQL(sqlUpdate);
            }
            else ok = true;
            if (ok)
            {



                string sql = @"UPDATE BANG_GIA_XE
                            SET TEN_BANG_GIA = @TEN_BANG_GIA,	                          
	                            DANG_AP_DUNG = @DANG_AP_DUNG,
	                            NGUOI_CAP_NHAT = @NGUOI_CAP_NHAT,
	                            NGAY_CAP_NHAT = GetDate() ,
                                MO_TA = @MO_TA                              
                                WHERE BANG_GIA_XE_ID=@BANG_GIA_XE_ID"
                            ;


                ok = SQLConnectWeb.ExecuteNonQuery(sql,
                        "@TEN_BANG_GIA", txtTenBangGia.Text,

                        "@DANG_AP_DUNG", (ckcApDung.Checked ? "Y" : "N"),
                        "@NGUOI_CAP_NHAT", UserLogin.USER_ID(this),
                        "@BANG_GIA_XE_ID", keyField.Value,
                         "@MO_TA", txtMoTa.Text.Replace("'", "")
                      ) > 0;

            }
            if (ok)
            {
                lblNgayCapNhat.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyyy HH:mm");
                lblNguoiCapNhat.Text = UserLogin.FULL_NAME(this);
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Cập nhật bảng giá không thành công!");
            }
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("QuanLyBangGiaVe.aspx"));
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string sql = string.Format("delete from {0} where {1}={2}", BANG_GIA_XE.sTableName, BANG_GIA_XE.cl_BANG_GIA_XE_ID, keyField.Value);
        if (SQLConnectWeb.ExecSQL(sql))
        {
            btnBack_Click(sender, e);
        }
        else
        {
            HelpControls.ShowMsgBox(this, "Xóa bảng giá không thành công!");
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        divChiTiet.Visible = false;
        keyField.Value = "";
        lblNgayCNCaption.Visible = false;
        lblNguoiCNCaption.Visible = false;
        txtMoTa.Text = "";
        txtTenBangGia.Text = "";
        lblNguoiCapNhat.Text = "";
        lblNgayCapNhat.Text = "";
        btnSave.Text = "Lưu";

        btnDelete.Visible = false;

        lblNgayTao.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyy HH:mm");
        lblNguoiTao.Text = UserLogin.FULL_NAME(this);
        txtTenBangGia.Focus();
    }
    protected void uploadImage_Unload(object sender, EventArgs e)
    {

    }
    protected void gridViewData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        DataKey row = gridViewData.DataKeys[int.Parse(e.CommandArgument.ToString())];
        if (e.CommandName == "cmdEdit")
        {
            //   GridViewRow row = gridViewData.Rows[];

            keyFieldDetail.Value = row.Values[BANG_GIA_XE_CT.cl_BANG_GIA_XE_CT_ID].ToString();
            txtBenDi.Text = row.Values[BANG_GIA_XE_CT.cl_BEN_DI].ToString();
            txtBenDen.Text = row.Values[BANG_GIA_XE_CT.cl_BEN_DEN].ToString();
            ddlTuyenDuong.SelectedValue = row.Values[BANG_GIA_XE_CT.cl_TUYEN_DUONG_ID].ToString();
            ddlLoaiXe.SelectedValue = row.Values[BANG_GIA_XE_CT.cl_LOAI_XE_ID].ToString();
            txtGiaVe.Text = row.Values[BANG_GIA_XE_CT.cl_GIA_VE].ToString();
            txtPhuThu.Text = row.Values[BANG_GIA_XE_CT.cl_PHU_THU].ToString();
            txtGhiChu.Text = row.Values[BANG_GIA_XE_CT.cl_GHI_CHU].ToString();
            btnSaveDetail.Text = "Cập nhật chi tiết";

        }
        else if (e.CommandName == "cmdDelete")
        {
            string delete = row.Values[BANG_GIA_XE_CT.cl_BANG_GIA_XE_CT_ID].ToString();
            // HelpControls.ShowMsgBoxConfirmDelete(this);
            string sql = string.Format("delete from {0} where {1}={2}", BANG_GIA_XE_CT.sTableName, BANG_GIA_XE_CT.cl_BANG_GIA_XE_CT_ID, delete);
            if (SQLConnectWeb.ExecSQL(sql))
            {
                //  HelpControls.ShowMsgBox(this, "Xóa dữ liệu thành công!");
                InitListDetail();
                if (delete == keyFieldDetail.Value)
                    btnNewDetail_Click(null, null);
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Dữ liệu đang được sử dụng!");
            }

        }
    }
    protected void gridViewData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((LinkButton)e.Row.Cells[1].Controls[0]).OnClientClick = "return confirm('Bạn có chắc là muốn xóa dữ liệu này?');";
        }
    }
    protected void btnSaveDetail_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(keyFieldDetail.Value))
        {

            bool ok = false;



            string sql = @"INSERT INTO BANG_GIA_XE_CT(BANG_GIA_XE_ID,	TUYEN_DUONG_ID,	LOAI_XE_ID,	GIA_VE,	PHU_THU,	GHI_CHU,	BEN_DI,	BEN_DEN)
VALUES(	@BANG_GIA_XE_ID,@TUYEN_DUONG_ID,	@LOAI_XE_ID	,	@GIA_VE,	@PHU_THU,@GHI_CHU,@BEN_DI,@BEN_DEN)";


            ok = SQLConnectWeb.ExecuteNonQuery(sql,
                    "@BANG_GIA_XE_ID", keyField.Value,
                    "@TUYEN_DUONG_ID", ddlTuyenDuong.SelectedValue,
                    "@LOAI_XE_ID", ddlLoaiXe.SelectedValue,
                    "@GIA_VE", HelpUtil.ParseDecimal(txtGiaVe.Text),
                    "@PHU_THU", HelpUtil.ParseDecimal(txtPhuThu.Text),
                    "@GHI_CHU", txtGhiChu.Text,
                    "@BEN_DI", txtBenDi.Text,
                    "@BEN_DEN", txtBenDen.Text
                  ) > 0;

            if (ok)
            {
                DataTable dt = SQLConnectWeb.GetTable(string.Format(@"select top 1 BANG_GIA_XE_CT_ID from BANG_GIA_XE_CT order by BANG_GIA_XE_CT_ID desc"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    keyFieldDetail.Value = dt.Rows[0]["BANG_GIA_XE_CT_ID"].ToString();
                    btnSaveDetail.Text = "Cập nhật chi tiết";
                    InitListDetail();

                }
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Thêm chi tiết cho bảng giá không thành công!");
            }
        }
        else
        {

            bool ok = false;


            string sql = @"UPDATE BANG_GIA_XE_CT
                        SET
	                        TUYEN_DUONG_ID = @TUYEN_DUONG_ID,
	                        LOAI_XE_ID = @LOAI_XE_ID,
	                        GIA_VE = @GIA_VE,
	                        PHU_THU = @PHU_THU,
	                        GHI_CHU = @GHI_CHU,
	                        BEN_DI = @BEN_DI,
	                        BEN_DEN = @BEN_DEN
                        where BANG_GIA_XE_CT_ID=@BANG_GIA_XE_CT_ID"
                        ;


            ok = SQLConnectWeb.ExecuteNonQuery(sql,

                "@TUYEN_DUONG_ID", ddlTuyenDuong.SelectedValue,
                "@LOAI_XE_ID", ddlLoaiXe.SelectedValue,
                "@GIA_VE", HelpUtil.ParseDecimal(txtGiaVe.Text),
                "@PHU_THU", HelpUtil.ParseDecimal(txtPhuThu.Text),
                "@GHI_CHU", txtGhiChu.Text,
                "@BEN_DI", txtBenDi.Text,
                "@BEN_DEN", txtBenDen.Text,
                  "@BANG_GIA_XE_CT_ID", keyFieldDetail.Value) > 0;



            if (!ok)
            {
                HelpControls.ShowMsgBox(this, "Cập nhật chi tiết bảng giá không thành công!");
            }
            else
                InitListDetail();
        }
    }
    protected void btnNewDetail_Click(object sender, EventArgs e)
    {
        txtGhiChu.Text = "";
        txtBenDen.Text = "";
        txtBenDi.Text = "";
        ddlLoaiXe.SelectedValue = "-1";
        ddlTuyenDuong.SelectedValue = "-1";
        txtGiaVe.Text = "";
        txtPhuThu.Text = "";
        keyFieldDetail.Value = "";
        btnSaveDetail.Text = "Lưu chi tiết";
    }
}
